// pages/login/login.js
import {reqLogin,reqUserInfo} from "../../apis/user.js"
import {toast} from "../../utils/extendApi"
import {userStore} from "../../store/userStore.js"
import {ComponentWithStore} from "mobx-miniprogram-bindings"
import { debounce } from 'miniprogram-licia'
ComponentWithStore({
  storeBindings:{
    store:userStore,
    fields:['token'],
    actions:['setToken','setUserInfo']
  },
  methods:{
    login:debounce(function () {
      wx.login({
        success: async({code}) => {
        if(code){
          const res =await reqLogin(code)
          // console.log(res);
          wx.setStorageSync('token', res.data.token)
          // 将数据存储到 store 对象中
          this.setToken(res.data.token)
          //获取用户信息
          this.getUserInfo()
          // 关闭当前页面，返回上一页或者返回多级页面
          wx.navigateBack()
        }else{
          toast({title:'授权失败，请稍后再试~~~'})
        }
        }
      })
     
        
    }, 500),
     // 获取用户信息
     async getUserInfo() {
      const { data } = await reqUserInfo()
      // 将用户信息存储到本地
     wx.setStorageSync('userInfo', data)
     // 将用户信息存储到 Store
     this.setUserInfo(data)
    }
  }
  
  
});
